from database.mysql import register_mysql
from database.redis import redis_connect
from test_middleware import init_middleware
from account.router import router as accountRouter
from test_user import router as userRouter
from test_dropbox import router as dpRouter
from test_email import router as emailRouter
from config import config
import uvicorn
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, Response, status, __version__
import sys
from pathlib import Path
from typing import Optional
from contextlib import asynccontextmanager

sys.path.append(str(Path(__file__).parent))


@asynccontextmanager
async def server_init(app: FastAPI):
    print("Server started")
    app.state.redis = await redis_connect()
    # logger_init()
    # db_init()
    # db_settings()
    # service_init()
    # send_email()
    async with register_mysql(app):
        yield print("yield in lifespan")

    # yield
    # print("waiting for next event")
    await app.state.redis.close()
    # logger()
    # db_close()
    # service_close()
    # send_email()
    print("Server closed")


app = FastAPI(debug=config.DEBUG_MODE,
              title="test",
              description="test here",
              lifespan=server_init)


app.mount(config.STATIC_URL, StaticFiles(
    directory=config.STATIC_DIR), name=config.STATIC_NAME)

init_middleware(app)

app.include_router(dpRouter, prefix="/dropbox", tags=["dropbox"])
app.include_router(userRouter, prefix="/user", tags=["user"])
app.include_router(accountRouter, prefix="/account", tags=["account"])
app.include_router(emailRouter, prefix="/email", tags=["email"])


@app.get("/server-status", include_in_schema=False)
async def server_status(response: Response, token: Optional[str]):
    if (token == "admin"):
        data = {"status": "ok", "fastapi version": __version__,
                "python version": sys.version_info}
        return data
    else:
        response.status = status.HTTP_404_NOT_FOUND
    return {"status": "not found"}


if __name__ == "__main__":
    uvicorn.run("test:app", port=8000, reload=True)
